<template>
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm :formItemList="formItemList" @search="(e) => {
          (searchlist = { ...e }), (currentPage = 1), getTableDataList();
        }
        ">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:tab>
      <EnumSlot @handleEvent="getEnumEvent" :selectIndex="selectIndex" :enumList="enumList"></EnumSlot>
    </template>
    <template v-slot:table>
      <TableData :isSelect="true" :tableThead="tableThead" :dataList="dataList" @selection-change="selectionChange">
        <template v-slot:outboundOrderType="{ row }">
          <span>
            {{ row.outboundOrderType == 1 ? "自行出库" : "销售出库" }}</span>
        </template>
        <template v-slot:shouldArriveNum="{ row }">
          <span>{{ row.shouldArriveNum
            }}{{ row.unit.symbol || row.unit.unitName }}</span>
        </template>
        <template v-slot:primaryQuantity="{ row }">
          <span>{{ row.primaryQuantity
            }}{{ row.unit.symbol || row.unit.unitName }}</span>
        </template>
        <template v-slot:slotOperate="{ row }">
          <template v-if="!row.index">
            <el-button v-if="codeList.indexOf('edit') !== -1 && forderStatus === 0" class="text-btn-cursor" type="text"
              size="small" @click="edit(row, 'edit')">
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button v-if="codeList.indexOf('revoke') !== -1 && forderStatus === 0" class="text-btn-cursor" type="text"
              size="small" @click="edit(row, 'check')">
              <i class="el-icon-edit-outline"></i>审核
            </el-button>
            <el-button v-if="codeList.indexOf('delete') !== -1 && forderStatus === 0"
              class="text-btn-cursor cursor-delete" type="text" size="small"
              @click="handleDelete([row.outboundOrderNo])">
              <i class="el-icon-delete"></i> 删除
            </el-button>
            <el-button v-if="forderStatus !== 0" class="text-btn-cursor" type="text" size="small"
              @click="edit(row, 'check')">
              <i class="el-icon-view"></i>查看详情
            </el-button>
          </template>
        </template>
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination  @size-Change="handleSizeChange" :size="pageSize"  @current-change="handleCurrentChange" :page="currentPage" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal="false"  :title="titleText" :visible.sync="dialogFormVisible" width="80%" @close="cancel('formData')">
        <el-form ref="formData" label-position="left" :model="formData" label-width="120px" :rules="rules"
          class="el-form">
          <el-form-item v-if="nowChanceStau === 'add'" label="出库形式 :" class="w100p">
            <el-button :type="outboundOrderType ? '' : 'primary'" @click="changeAddWays(0)">销售出库</el-button>
            <el-button :type="!outboundOrderType ? '' : 'primary'" @click="changeAddWays(1)">自行出库</el-button>
          </el-form-item>
          <el-form-item v-if="outboundOrderType === 0 && nowChanceStau === 'add'" label="源头单据类型 :" prop="sourceDocType"
            class="w50p" :rules="[
        {
          required: true,
          message: '源头单据类型不能为空',
          trigger: 'change',
        },
      ]">
            <el-select class="w50p" v-model="formData.sourceDocType" placeholder="请选择源头单据类型" clearable>
              <el-option v-for="(items, indexs) in sourceDocTypeList" :key="indexs" :label="items.name"
                :value="items.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="outboundOrderType === 0 && nowChanceStau === 'add'" label="源头单号 :" prop="sourceDocNo"
            class="w100p" :rules="[
        {
          required: true,
          message: '源头单明细号不能为空',
          trigger: 'change',
        },
      ]">
            <el-select v-model="formData.sourceDocNo" placeholder="请选择源头单号" clearable class="w100p"
              @change="getOrderDetailList">
              <el-option v-for="(items, indexs) in sourceDocNoList" :key="indexs" :label="items.saleOrderNo"
                :value="items.saleOrderNo" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="nowChanceStau === 'add' && outboundOrderType === 0" label="选择出库商品 :" class="w100p">
            <el-checkbox-group v-model="formData.outGoodsList" @change="chooseGoods">
              <el-checkbox v-for="(items, indexs) in outGoodsList" :key="indexs" :label="items">{{ items.materialName
                }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <div v-for="(orderDetail, index) in formData.putInStorageList" :key="orderDetail.key" class="orderDetail">
            <div v-if="nowChanceStau === 'add'" class="goods w100p">
              出库货{{ index + 1 }}
            </div>
            <el-form-item label="出库货名 :"  :prop="'putInStorageList.' + index + '.materialNo'" class="w50p" :rules="[
        {
          required: true,
          message: '出库货名不能为空',
          trigger: 'change',
        },
      ]">
              <el-select v-model="orderDetail.materialNo" placeholder="请选择出库货名称" filterable clearable class="w100p"
                :disabled="outboundOrderType === 0 || nowChanceStau === 'check'" @change="getGoods($event, index)">
                <el-option v-for="(items, indexs) in materialList" :key="indexs" :label="items.materialName"
                  :value="items.materialNo" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="outboundOrderType === 1" label="选择货品批次:"
              :prop="'putInStorageList.' + index + '.batchObj'" :rules="[
        { required: true, message: '请选择货品批次', trigger: 'blur' }
      ]" class="w50p">
              <el-select v-model="orderDetail.batchObj" placeholder="点击选择" filterable clearable class="w100p"
                value-key="onHandQuantityId" :disabled="nowChanceStau === 'check'"
                @change="batchObjChange($event, index)">
                <el-option v-for="item in batchList" :key="item.onHandQuantityId" :label="'批号: ' +
        (item.batchFile.lotNumber === undefined
          ? ''
          : item.batchFile.lotNumber) +
        ',  该批次现存主数量 : ' +
        item.onHandQuantity +
        (item.cUnit ? item.cUnit.symbol || item.cUnit.unitName : '') +
        ',  生产日期 : ' +
        item.batchFile.produceDate +
        ',  失效日期 : ' +
        item.batchFile.expirationDate
        " :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="出货仓库 :" :prop="'putInStorageList.' + index + '.stordocNo'" class="w50p" :rules="[
        {
          required: true,
          message: '出货仓库不能为空',
          trigger: 'change',
        },
      ]">
              <el-select v-model="orderDetail.stordocNo" placeholder="请选择出货仓库" clearable disabled class="w100p">
                <el-option v-for="(items, indexs) in stordocList" :key="indexs" :label="items.stordocName"
                  :value="items.stordocNo" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="outboundOrderType === 1 && nowChanceStau === 'add'" label="现存主数量 :"
              :prop="'putInStorageList.' + index + '.nowQuantity'" class="w50p" :rules="[
        { required: true, message: '数量不能为空', trigger: 'blur' },
        {
          pattern: /^\d+$/,
          message: '值该为正整数',
          trigger: ['change', 'blur'],
        },
      ]">
              <el-input v-model="orderDetail.nowQuantity" clearable disabled placeholder="现存主数量">
                <template slot="append">
                  <span v-show="items.unitNo == orderDetail.unitNo" v-for="(items, indexs) in unitList" :key="indexs">
                    {{ items.symbol || items.unitName }}
                  </span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item :label="outboundOrderType === 0 ? '实出数量 :' : '出货数量 :'"
              :prop="'putInStorageList.' + index + '.confirmQuantity'" class="w50p" :rules="[
        { required: true, message: '数量不能为空', trigger: 'blur' },
        {
          pattern:
            /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
          message: '值该为大于0的数',
          trigger: ['blur', 'change'],
        },
      ]">
              <el-input v-model="orderDetail.confirmQuantity" clearable class="one" placeholder="请输入数量"
                :disabled="nowChanceStau === 'check'" @input="getMainQuantity($event, index)">
                <template slot="append">
                  <span v-show="items.unitNo == orderDetail.castUnitNo" v-for="(items, indexs) in unitList"
                    :key="indexs">
                    {{ items.symbol || items.unitName }}
                  </span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="单位 :" :prop="'putInStorageList.' + index + '.castUnitNo'" class="w50p" :rules="[
        { required: true, message: '单位不能为空', trigger: 'change' },
      ]">
              <el-select v-model="orderDetail.castUnitNo" placeholder="请选择单位" clearable class="w100p"
                :disabled="outboundOrderType === 0">
                <el-option v-for="(items, indexs) in unitList" :key="indexs" :label="items.symbol || items.unitName"
                  :value="items.unitNo" />
              </el-select>
            </el-form-item>
            <el-form-item label="换算率 :" :prop="'putInStorageList.' + index + '.exchangeRate'" class="w50p" :rules="[
        {
          pattern: /^\d+$/,
          message: '值该为正整数',
          trigger: ['change', 'blur'],
        },
        {
          required: true,
          message: '换算率不能为空',
          trigger: 'change',
        },
      ]">
              <el-input v-model="orderDetail.exchangeRate" clearable :disabled="outboundOrderType === 0"
                placeholder="请输入换算率" @input="getMainQuantity($event, index)" />
            </el-form-item>
            <el-form-item v-if="outboundOrderType === 0" label="应出数量 :"
              :prop="'putInStorageList.' + index + '.shouldSendNum'" class="w50p" :rules="[
        {
          pattern:
            /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
          message: '值该为大于0的数',
          trigger: ['change', 'blur'],
        },
        { required: true, message: '数量不能为空', trigger: 'change' },
      ]">
              <el-input v-model="orderDetail.shouldSendNum" clearable disabled placeholder="请输入应出数量" />
            </el-form-item>
            <div class="w50p">
              <el-form-item label="主数量/单位:" :prop="'putInStorageList.' + index + '.primaryQuantity'" :rules="[
        {
          pattern:
            /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
          message: '值该为大于0的数',
          trigger: ['change', 'blur'],
        },
        {
          required: true,
          message: '数量不能为空',
          trigger: 'change',
        },
      ]">
                <el-input v-model="orderDetail.primaryQuantity" clearable disabled placeholder="主数量">
                  <template slot="append">
                    <span v-show="items.unitNo == orderDetail.unitNo" v-for="(items, indexs) in unitList" :key="indexs">
                      {{ items.symbol || items.unitName }}
                    </span>
                  </template>
                </el-input>
              </el-form-item>
            </div>
            <el-form-item label="单价/元 :" :prop="'putInStorageList.' + index + '.price'" class="w50p" :rules="[
        {
          pattern:
            /^((0\.){1}[0-9]*[1-9]+[0-9]*)$|^([1-9][0-9]*((\.)?[0-9]+)?)$/,
          message: '值该大于0',
          trigger: ['change', 'blur'],
        },
      ]">
              <el-input v-model="orderDetail.price" clearable placeholder="请输入单价" :disabled="outboundOrderType === 0" />
            </el-form-item>
            <el-form-item label="总金额/元 :" :prop="'putInStorageList.' + index + '.totalPrice'" class="w50p" :rules="[
        {
          pattern:
            /^((0\.){1}[0-9]*[1-9]+[0-9]*)$|^([1-9][0-9]*((\.)?[0-9]+)?)$/,
          message: '值该大于0',
          trigger: ['change', 'blur'],
        },
      ]">
              <el-input v-model="orderDetail.totalPrice" clearable placeholder="请输入金额"
                :disabled="outboundOrderType === 0" />
            </el-form-item>
            <el-form-item v-if="outboundOrderType === 1" label="生产日期 :"
              :prop="'putInStorageList.' + index + '.produceDate'" class="w50p" :rules="[
        {
          required: true,
          message: '生产日期不能为空',
          trigger: 'change',
        },
      ]">
              <el-date-picker v-model="orderDetail.produceDate" type="date" value-format="yyyy-MM-dd" disabled clearable
                class="w100p" placeholder="请选择时间" />
            </el-form-item>
            <el-form-item v-if="outboundOrderType === 1" label="失效日期 :"
              :prop="'putInStorageList.' + index + '.expirationDate'" class="w50p" :rules="[
        {
          required: true,
          message: '失效日期不能为空',
          trigger: 'change',
        },
      ]">
              <el-date-picker v-model="orderDetail.expirationDate" type="date" value-format="yyyy-MM-dd" clearable
                disabled class="w100p" placeholder="请选择时间" @change="getCount($event, index)" />
            </el-form-item>
            <el-form-item label="出库日期 :" :prop="'putInStorageList.' + index + '.outTime'" class="w50p" :rules="[
        { required: true, message: '出货不能为空', trigger: 'change' },
      ]">
              <el-date-picker v-model="orderDetail.outTime" type="datetime" value-format="yyyy-MM-dd HH:mm" clearable
                class="w100p" :disabled="nowChanceStau === 'check'" placeholder="请选择时间" />
            </el-form-item>
            <el-form-item v-if="nowChanceStau === 'check'" label="审核状态 :"
              :prop="'putInStorageList.' + index + '.forderStatus'" class="w50p" :rules="[
        {
          required: true,
          message: '审核状态不能为空',
          trigger: 'change',
        },
      ]">
              <el-select v-model="orderDetail.forderStatus" placeholder="请选择审核状态" clearable class="w100p">
                <el-option v-for="(items, indexs) in forderStatusList" :key="indexs" :label="items.name"
                  :value="items.value" />
              </el-select>
            </el-form-item>
            <div class="btnlist">
              <div v-if="nowChanceStau === 'add' && outboundOrderType === 1">
                <el-button type="info" circle @click="delOrderDetail(index)">
                  <i class="el-icon-minus"></i>
                </el-button>
                <el-button type="info" circle @click="addOrderDetail">
                  <i class="el-icon-plus"></i>
                </el-button>
              </div>
            </div>
          </div>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button v-if="forderStatus === 0" class="zh-button-two" type="primary" @click="save('formData')">保
            存</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script src="">
import MainSlot from "@/components/MainSlot";
import Pagination from "@/components/Pagination";
import SearchForm from "@/components/SearchForm";
import TableData from "@/components/TableData";
import BtnSlot from "@/components/BtnSlot";
import EnumSlot from "@/components/EnumSlot";

import Table from "@/components_yy/table/table.vue";
import { mymixin } from "@/utils/mixins";
import unitApi from "@/api/basic-info-manage/unit-manage"; // 单位
import materialApi from "@/api/basic-info-manage/agr-source-base-Manage"; // 物料
import saleOrderApi from "@/api/livestock-manage/sale-manage/sale-order"; // 销售订单
import saleOrderDetailApi from "@/api/livestock-manage/sale-manage/sale-order-detail"; // 销售订单明细
import warehouseApi from "@/api/livestock-manage/storage-manage/warehouse-manage"; // 仓库
import personApi from "@/api/livestock-manage/personnel-cost-mansge/staff-manage"; // 人员
import deliveryDetailApi from "@/api/livestock-manage/sale-manage/delivery-detail"; // 出货明细
import outStorage from "@/api/livestock-manage/sale-manage/out-storage"; // 出库
import handQuantityApi from "@/api/livestock-manage/storage-manage/quantity-on-hand"; // 现存量
import nowpagereqquery from "@/api/digtalOperation/production-batch-manage/create-production-batch/index";
import { mapGetters } from "vuex";
export default {
  name: "SheepInformation",
  components: {
    SearchForm,
    Table,
    MainSlot,
    TableData,
    EnumSlot,
    BtnSlot,
    Pagination,
  },
  mixins: [mymixin],
  data() {
    return {
      total: 100,
      selectIndex: 0,
      currentPage: 1,
      dataList: [],
      tableThead: [
        { isShow: true, label: "出库单号", prop: "outboundOrderNo" },
        { isShow: true, label: "出库形式", slotName: "outboundOrderType" },
        { isShow: true, label: "仓库", prop: "stordocName" },
        { isShow: true, label: "出库货名", prop: "materialName" },
        { isShow: true, label: "应出数量", slotName: "shouldSendNum" },
        { isShow: true, label: "实出数量", prop: "confirmQuantity" },
        { isShow: true, label: "主数量", prop: "primaryQuantity" },
        { isShow: true, label: "换算率", prop: "exchangeRate" },
        { isShow: true, label: "单价/元", prop: "price" },
        { isShow: true, label: "总金额/元", prop: "totalPrice" },
        { isShow: true, label: "出库日期", prop: "outTime" },
        { isShow: true, label: "生产日期", prop: "produceDate" },
        { isShow: true, label: "失效日期", prop: "expirationDate" },
        { isShow: true, label: "操作", slotName: "slotOperate", width: "200" },
      ],
      btnList: ["add", "delete"],
      searchlist: {},
      tableColumn: [],
      batchList: [],
      formItemList: [
        {
          label: "出库形式",
          type: "select",
          selectOptions: [
            { text: "销售出库", value: 0 },
            { text: "自行出库", value: 1 },
          ],
          param: "outboundOrderType",
          defaultSelect: "",
          multiple: false,
          isShow: true,
        },
        {
          label: "出库单号",
          type: "input",
          param: "outboundOrderNo",
          isShow: true,
        },
        {
          selectOptions: [],
          label: "出库仓库",
          type: "input",
          param: "stordocName",
          defaultSelect: "",
          multiple: false,
          isShow: true,
        },
        {
          label: "出库货名",
          type: "input",
          param: "materialName",
          selectOptions: [],
          defaultSelect: "",
          multiple: false,
          isShow: true,
        },
      ],
      forderStatus: 0, // 审核状态
      toAdd: {},
      outboundOrderType: 0,
      arrivalGoodsList: [],
      outGoodsList: [],
      selectedStaffList: [],
      personList: [],
      unitList: [],
      stordocList: [], // 仓库
      putInorderList: [], // 入库单号
      materialList: [], // 货名
      batchNoList: [], // 批次号
      warehousingTypeList: [
        { name: "成品", value: "成品" },
        { name: "半成品", value: "半成品" },
        { name: "原材料", value: "原材料" },
      ], // 出库类型
      sourceDocTypeList: [
        { name: "采购", value: "采购" },
        { name: "销售", value: "销售" },
      ],
      sourceDocNoList: [], // 所有采购订单号
      associatedDocumentTypeList: [
        { name: "采购明细", value: "采购明细" },
        { name: "销售明细", value: "销售明细" },
      ],
      associatedDocumentNoList: [], // 单个订单所有明细
      forderStatusList: [
        { name: "未审核", value: 0 },
        { name: "审核通过", value: 1 },
        { name: "审核未通过", value: 2 },
      ],
      formData: {
        sourceDocType: "销售",
        sourceDocNo: "",
        putInStorageList: [],
      },
      enumList: [
        { label: "未审核", type: 0 },
        { label: "审核通过", type: 1 },
        { label: "审核不通过", type: 2 },
      ],
      table_config: [],
      formDatalists: [
        {
          type: "input",
          porp: "outboundOrderNo",
          selectValue: "outboundOrderNo", // input Select Checkbox TimePicker
          typeObj: {},
          name: "出库单号",
          required: true,
        },
        {
          type: "Select",
          porp: "outboundOrderType",
          selectValue: "outboundOrderType", // input Select Checkbox TimePicker
          typeObj: {
            list: [
              { name: "销售出库", value: 0 },
              { name: "自行出库", value: 1 },
            ],
          },
          name: "出库形式",
          required: true,
        },
        {
          type: "Select",
          porp: "stordocName",
          selectValue: "stordocNo", // input Select Checkbox TimePicker
          typeObj: {},
          name: "仓库",
          required: true,
        },
        {
          type: "Select",
          porp: "materialName",
          selectValue: "materialNo", // input Select Checkbox TimePicker
          typeObj: {},
          name: "出库货名",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "shouldSendNum",
          typeObj: {},
          name: "应出数量",
          required: true,
          notSearch: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "confirmQuantity",
          typeObj: {},
          name: "实出数量",
          required: true,
          notSearch: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "primaryQuantity",
          typeObj: {},
          name: "主数量",
          required: true,
          notSearch: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "exchangeRate",
          typeObj: {},
          name: "换算率",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "price",
          typeObj: {},
          name: "单价/元",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalPrice",
          typeObj: {},
          name: "总金额/元",
          required: true,
        },
        {
          type: "date", // input Select Checkbox TimePicker
          prop: "outTime",
          typeObj: {},
          name: "出库日期",
          required: true,
        },
        {
          type: "date", // input Select Checkbox TimePicker
          prop: "produceDate",
          typeObj: {},
          name: "生产日期",
          required: true,
        },
        {
          type: "date", // input Select Checkbox TimePicker
          prop: "expirationDate",
          typeObj: {},
          name: "失效日期",
          required: true,
        },
      ],
      rules: {},
      selectionList: [],
    };
  },
  computed: {
    ...mapGetters(['codeList']),
  },
  watch: {
    formData: {
      deep: true,
      handler(val) {
        if (val.putInStorageList) {
          val.putInStorageList.forEach((item, index) => {
            console.log(item.exchangeRate && item.arriveNum,item.exchangeRate8*item.arriveNum)
            if (item.exchangeRate && item.arriveNum) {
              this.formData.putInStorageList[index].primaryQuantity =
                item.exchangeRate * item.arriveNum;
            }
          });
        }
      },
    },
  },
  created() {
    let list = [];
    this.formDatalists.map((el) => {
      let obj = {
        prop: el.prop,
        label: el.name,
        minWidth: "140px",
      };
      if (
        [
          "outboundOrderType",
          "shouldSendNum",
          "confirmQuantity",
          "primaryQuantity",
        ].includes(el.prop)
      ) {
        obj.slotName = el.prop;
      }
      list.push(obj);
    });
    list.push({
      prop: "operation",
      label: "操作",
      slotName: "operation",
      width: "180",
    });
    this.tableColumn = list;

    this.getMaterialList();
    this.getstordocList();
    this.getUnitList();
    this.getOederList();
    this.getPersonList();
    this.getSourceDocNoList();
    this.toAdd = this.$route.params;
    console.log(this.toAdd);
    this.getTableDataList();
  },
  mounted() { },
  methods: {
    // 多选方法
    selectionChange(val) {
      this.selectionList = val || [];
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleSizeChange(size){
      this.pageSize = size;
      this.getTableDataList();
    },
    setOptions(param) {
      let options = [];
      if (param == "materialNo" && this.materialList.length) {
        this.materialList.forEach((item) => {
          options.push({ text: item.materialName, value: item.materialNo });
        });
      } else if (param == "stordocNo" && this.stordocList.length) {
        this.stordocList.forEach((item) => {
          options.push({ text: item.stordocName, value: item.stordocNo });
        });
      }
      return options;
    },
    putInDate(index) {
      if (!typeof index === "number") return null;
      const self = this;
      // 入库
      return {
        disabledDate(time) {
          if (self.formData.putInStorageList[index].produceDate) {
            //  如果结束时间不为空，则小于结束时间
            return (
              new Date(
                self.formData.putInStorageList[index].produceDate
              ).getTime() >= time.getTime()
            );
          } else {
            // return time.getTime() > Date.now(); // 开始时间不选时，结束时间最大值小于等于当天
            return null;
          }
        },
      };
    },
    // 限制前面日期不能低于后面日期
    produceDate(index) {
      if (!typeof index === "number") return null;
      const self = this;
      // 生产日期
      return {
        disabledDate(time) {
          if (
            self.formData.putInStorageList[index].expirationDate &&
            self.formData.putInStorageList[index].intoTime
          ) {
            let a = new Date(
              self.formData.putInStorageList[index].expirationDate
            ).getTime();
            let b = new Date(
              self.formData.putInStorageList[index].intoTime
            ).getTime();
            return a > b ? b <= time.getTime() : a <= time.getTime();
          } else if (self.formData.putInStorageList[index].expirationDate) {
            return (
              new Date(
                self.formData.putInStorageList[index].expirationDate
              ).getTime() <= time.getTime()
            );
          } else if (self.formData.putInStorageList[index].intoTime) {
            // return time.getTime() > Date.now(); // 开始时间不选时，结束时间最大值小于等于当天
            return (
              new Date(
                self.formData.putInStorageList[index].intoTime
              ).getTime() <= time.getTime()
            );
          } else {
            return null;
          }
        },
      };
    },
    expirationDate(index) {
      if (!typeof index === "number") return null;
      // 失效日期
      const self = this;
      return {
        disabledDate(time) {
          if (self.formData.putInStorageList[index].produceDate) {
            //  如果开始时间不为空，则结束时间大于开始时间
            self.time = new Date();
            return (
              new Date(
                self.formData.putInStorageList[index].produceDate
              ).getTime() >= time.getTime()
            );
          } else {
            // return time.getTime() > Date.now(); // 开始时间不选时，结束时间最大值小于等于当天
            return null;
          }
        },
      };
    },
    arrivalToputin() {
      deliveryDetailApi
        .queryListByDeliveryNo(this.toAdd.arriveOrderNo)
        .then((res) => {
          if (res.code === 1) {
            this.$set(this.formData, "sourceDocType", "销售");
            this.formData.sourceDocNo = res.data[0].saleOrderNo;
            this.$set(this.formData, "outGoodsList", []);
            this.outGoodsList = res.data;
            this.$set(this.formData, "outGoodsList", res.data);
            this.chooseGoods(res.data);
          }
        });
      this.nowChanceStau = "add";
      this.titleText = "添加出库";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },

    // 判断货存量
    getMainQuantity(e, index) {
      this.formData.putInStorageList[index].primaryQuantity =
        e * this.formData.putInStorageList[index].exchangeRate;
      if (
        this.formData.putInStorageList[index].primaryQuantity >
        this.formData.putInStorageList[index].nowQuantity
      ) {
        this.$message.warning("出货数量大于现存数量，请重新选择出货数量");
        this.formData.putInStorageList[index].confirmQuantity = "";
      }
    },

    // 获取源头单号
    getSourceDocNoList() {
      saleOrderApi.conditionQuery({ forderStatus: 1 }).then((res) => {
        if (res.code === 1) {
          this.sourceDocNoList = res.data;
        }
      });
    },
    // 添加一个出库单
    addOrderDetail() {
      nowpagereqquery
        .addcode("OUTBOUND_ORDER")
        .then((res) => {
          this.formData.putInStorageList.push({
            outboundOrderType: this.outboundOrderType,
            warehousingType: "",
            stordocNo: "",
            materialNo: "",
            batchNo: "",
            lotNumber: "",
            primaryQuantity: "",
            unitNo: "",
            arriveNum: "",
            castUnitNo: "",
            exchangeRate: "",
            shouldSendNum: "",
            price: "",
            totalPrice: "",
            outTime: "",
            sourceDocType: "销售",
            sourceDocNo: "",
            associatedDocumentType: "销售明细",
            assassociatedDocumentNo: "",
            weight: "",
            volume: "",
            packNum: "",
            produceDate: "",
            expirationDate: "",
            forderStatus: 0,
            organizationNo: sessionStorage.organizationNo,
            key: Date.now(),
            outboundOrderNo: res.data,
          });
        })
        .catch((err) => {
          this.$message({
            message: err,
            type: "warning",
          });
        });
    },
    // 删除一个出库单
    delOrderDetail(index) {
      console.log(this.formData.putInStorageList);
      if (this.formData.putInStorageList.length === 1) {
        return;
      } else {
        this.formData.putInStorageList.splice(index, 1);
      }
    },
    //获取选中Enum
    getEnumEvent(enumInfo) {
      console.log(enumInfo);
      this.selectIndex = enumInfo.index || 0;
      if (this.selectIndex === 0) {
        this.addActive = true;
      } else {
        this.addActive = false;
      }
      this.currentPage = 1;
      this.forderStatus = this.selectIndex;
      this.search();
    },
    // 获取所有物料
    getMaterialList() {
      materialApi.getqueryList({}).then((res) => {
        if (res.code === 1) {
          this.materialList = res.data;
          console.log(this.materialList)
          let list = [];
          this.materialList.forEach((item) => {
            list.push({
              value: item.materialNo,
              text: item.materialName,
            });
          });

          this.$set(this.formItemList[3], "selectOptions", list);
          console.log(list, this.formItemList[3]);
          this.$set(this.formDatalists[4], "typeObj", {
            list: res.data,
            listName: ["materialName", "materialNo"],
          });
          this.setOptions(this.formItemList, "materialNo", res.data);
        }
      });
    },
    // 获取人员列表
    getPersonList() {
      personApi.getStaffListByCondition().then((res) => {
        if (res.code === 1) {
          this.personList = res.data;
          let list = [];
          res.data.forEach((item) => {
            list.push({
              name: item.person.name,
              value: item.personNo,
            });
          });
          this.formDatalists.forEach((item, index) => {
            if (item.prop === "receiverName") {
              this.$set(this.formDatalists[index].typeObj, "list", list);
            }
          });
        }
      });
    },
    // 获取所有销售订单
    getOederList() {
      saleOrderApi
        .conditionQuery({ completeStatus: false, forderStatus: 1 })
        .then((res) => {
          if (res.code === 1) {
            let list = [];
            res.data.forEach((item) => {
              list.push({
                name: item.orderNo,
                value: item.orderNo,
              });
            });
            this.formDatalists.forEach((item, index) => {
              if (item.prop === "orderNo") {
                this.$set(this.formDatalists[index].typeObj, "list", list);
              }
            });
            this.formDatalists.forEach((item, index) => {
              if (item.prop === "personName") {
                this.$set(this.formDatalists[index].typeObj, "list", list);
              }
            });
          }
        });
    },
    // 获取仓库
    getstordocList() {
      warehouseApi.conditionQuery({}).then((res) => {
        if (res.code === 1) {
          this.stordocList = res.data;
          this.formDatalists.forEach((item, index) => {
            if (item.prop === "stordocName") {
              this.$set(this.formDatalists[index], "typeObj", {
                list: res.data,
                listName: ["stordocName", "stordocNo"],
              });
            }
          });
        }
      });
    },
    // 获取单位列表X
    getUnitList() {
      unitApi.getPlantingUnitListByCondition({}).then((res) => {
        if (res.code === 1) this.unitList = res.data;
      });
    },
    // 选择现存量来填充其他属性
    batchObjChange(event, index) {
      console.log(event);
      this.formData.putInStorageList[index].batchNo = event.batchNo;
      this.formData.putInStorageList[index].stordocNo = event.stordocNo;
      this.formData.putInStorageList[index].lotNumber =
        event.batchFile.lotNumber;
      this.formData.putInStorageList[index].castUnitNo = event.castUnitNo;
      this.formData.putInStorageList[index].unitNo = event.unitNo;
      this.formData.putInStorageList[index].exchangeRate = event.changerate;
      this.formData.putInStorageList[index].nowQuantity = event.onHandQuantity;
      this.formData.putInStorageList[index].expirationDate =
        event.batchFile.expirationDate;
      this.formData.putInStorageList[index].produceDate =
        event.batchFile.produceDate;
      this.formData.putInStorageList[index].nowQuantity = event.onHandQuantity;
    },
    timeEvent(event, prop) {
      if (prop === "arriveTime") {
        this.formData.putInStorageList.forEach((item, index) => {
          this.$set(this.formData.putInStorageList[index], "arriveTime", event);
        });
      }
    },
    // 获取单个商品
    getGoods(event, index) {
      this.formData.putInStorageList[index].batchObj = {};
      handQuantityApi.conditionQuery({ materialNo: event }).then((res) => {
        if (res.code === 1) {
          this.batchList = res.data;
        }
      });
    },
    // 选择出货商品
    chooseGoods(e) {
      this.$set(this.formData, "putInStorageList", e);
      this.formData.putInStorageList[0].outboundOrderNo = this.outboundOrderNo;
      this.formData.putInStorageList.forEach((item, index) => {
        this.formData.putInStorageList[index].sourceDocType =
          this.formData.sourceDocType;
        this.formData.putInStorageList[index].sourceDocNo =
          this.formData.sourceDocNo;
        this.formData.putInStorageList[index].associatedDocumentType =
          this.formData.sourceDocType + "明细";
        this.formData.putInStorageList[index].associatedDocumentNo =
          item.orderDetailNo;
        this.$set(
          this.formData.putInStorageList[index],
          "shouldSendNum",
          item.confirmQuantity || item.shouldSendNum
        );
        this.$set(this.formData.putInStorageList[index], "forderStatus", 0);
        this.formData.putInStorageList[index].key = Date.now();
        this.formData.putInStorageList[index].outboundOrderType =
          this.outboundOrderType;
      });
    },
    // 获取订单详细列表
    getOrderDetailList(e) {
      saleOrderDetailApi.queryListBySaleOrderNo(e).then((res) => {
        if (res.code === 1) {
          this.$set(this.formData, "outGoodsList", []);
          this.outGoodsList = res.data;
          this.$set(this.formData, "outGoodsList", [this.outGoodsList[0]]);
          this.chooseGoods([this.outGoodsList[0]]);
        }
      });
    },
    getTableDataList() {
      this.loading = false;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        organizationNo: sessionStorage.organizationNo,
        breedTypeNo: sessionStorage.breedTypeNo,
        entity: {
          forderStatus: this.forderStatus,
          ...this.searchlist,
          startTime: this.searchlist.outTime
            ? this.searchlist.outTime + " 00:00:00"
            : "",
          endTime: this.searchlist.outTime
            ? this.searchlist.outTime + " 23:59:59"
            : "",
        },
      };
      delete params.entity.intoTime;
      outStorage.pageQuery(params).then((res) => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.getTableDataList();
          }
          if (this.toAdd.isTo === "toAdd") {
            this.arrivalToputin();
          }
          this.toAdd = {};
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map((item) => item.outboundOrderNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      outStorage
        .numberBatchDel({ noList: this.selectedStaffList })
        .then((res) => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        });
    },
    handleDelete(val) {
      console.log(val, "valvalvalvalvalv");
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          outStorage.numberDel(val).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => { });
    },
    changeAddWays(e) {
      this.outboundOrderType = e;
      if (this.outboundOrderType === 0) {
        this.formData = {
          sourceDocNo: "",
          sourceDocType: "销售",
          putInStorageList: [],
        };
      }
      if (this.outboundOrderType === 1) {
        this.formData = {
          putInStorageList: [
            {
              outboundOrderType: this.outboundOrderType,
              warehousingType: "",
              stordocNo: "",
              materialNo: "",
              batchNo: "",
              lotNumber: "",
              primaryQuantity: "",
              unitNo: "",
              arriveNum: "",
              castUnitNo: "",
              exchangeRate: "",
              shouldSendNum: "",
              price: "",
              totalPrice: "",
              outTime: "",
              weight: "",
              volume: "",
              packNum: "",
              produceDate: "",
              expirationDate: "",
              forderStatus: 0,
              organizationNo: sessionStorage.organizationNo,
              key: Date.now(),
            },
          ],
        };
      }
      // 获取入库订单编号
      nowpagereqquery.addcode("OUTBOUND_ORDER").then((res) => {
        this.outboundOrderNo = res.data;
        this.outboundOrderType === 1 &&
          (this.formData.putInStorageList[0].outboundOrderNo = res.data);
      });
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag);
      if (flag == "add") {
        if (this.forderStatus === 0) {
          this.add();
        } else {
          this.$message.warning("请切换至未审核！");
        }
      } else if (flag == "delete") {
        if (this.selectionList.length > 0) {
          let newselectedList = [];
          this.selectionList.forEach((item) => {
            newselectedList.push(item.outboundOrderNo);
          });
          this.handleDelete(newselectedList);
        } else {
          this.$message.warning("请先选择表单数据项后再删除！");
        }
      }
      this.addEditFlag = flag;
    },
    add() {
      this.formData.putInStorageList = [];
      this.arrivalGoodsList = [];
      if (this.outboundOrderType === 0) {
        this.formData = {
          sourceDocNo: "",
          sourceDocType: "销售",
          putInStorageList: [],
        };
      }
      if (this.outboundOrderType === 1) {
        this.formData = {
          putInStorageList: [
            {
              outboundOrderType: this.outboundOrderType,
              warehousingType: "",
              stordocNo: "",
              materialNo: "",
              batchNo: "",
              lotNumber: "",
              primaryQuantity: "",
              unitNo: "",
              arriveNum: "",
              castUnitNo: "",
              exchangeRate: "",
              shouldSendNum: "",
              price: "",
              totalPrice: "",
              outTime: "",
              weight: "",
              volume: "",
              packNum: "",
              produceDate: "",
              expirationDate: "",
              forderStatus: 0,
              organizationNo: sessionStorage.organizationNo,
              key: Date.now(),
            },
          ],
        };
      }
      // 获取入库订单编号
      nowpagereqquery.addcode("OUTBOUND_ORDER").then((res) => {
        this.outboundOrderNo = res.data;
      });
      this.nowChanceStau = "add";
      this.titleText = "添加出库";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    edit(row, e) {
      this.outboundOrderType = row.outboundOrderNo;
      this.$set(this.formData, "putInStorageList", [
        { key: Date.now(), ...row },
      ]);
      this.nowChanceStau = e;
      let a = e === "check" ? "审核" : "修改出库";
      this.titleText = a;
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    kookInfo(e) {
      this.formData = {};
      deliveryDetailApi.queryListByDeliveryNo(e).then((res) => {
        if (res.code === 1) {
          this.$set(this.formData, "putInStorageList", res.data);
        }
      });
      this.nowChanceStau = "kookInfo";
      this.titleText = "查看出货明细";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    addDetail(e, index) {
      let validateFieldList = [];
      this.$refs["formData"].validateField(
        [
          "putInStorageList." + index + ".materialNo",
          "putInStorageList." + index + ".confirmQuantity",
          "putInStorageList." + index + ".castUnitNo",
          "putInStorageList." + index + ".unitNo",
          "putInStorageList." + index + ".exchangeRate",
          "putInStorageList." + index + ".primaryQuantity",
          "putInStorageList." + index + ".price",
          "putInStorageList." + index + ".packNum",
          "putInStorageList." + index + ".totalPrice",
          "putInStorageList." + index + ".address",
        ],
        (valid) => {
          if (!valid) {
            validateFieldList.push(valid);

            // 因为我这里总共校验了三个字段,所有最终三个字段都校验成功之后,数组中会有三个""
            if (
              validateFieldList.length === 10 &&
              validateFieldList.every((item) => item === "")
            ) {
              saleOrderDetailApi.add(e).then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  saleOrderDetailApi.numberQuery(e.orderNo).then((res) => {
                    this.$set(this.formData, "putInStorageList", res.data);
                  });
                } else {
                  this.$message.warning(res.msg || "添加失败");
                }
              });
            }
            // 校验不通过走这里
            return;
          } else {
            return false;
          }
        }
      );
    },
    editDetail(e) {
      this.$confirm("确定修改该条数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          saleOrderDetailApi.edit(e).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
            } else {
              this.$message.warning(res.msg || "修改失败");
            }
          });
        })
        .catch(() => { });
    },
    delDetial(e, index) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          saleOrderDetailApi.numberQuery(e.orderNo).then((res) => {
            if (res.data.length <= 1) {
              this.$message.warning("已是最后一条数据禁止删除");
            } else {
              saleOrderDetailApi.numberDel(e.orderDetailNo).then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.formData.putInStorageList.splice(index, 1);
                } else {
                  this.$message.warning(res.msg || "删除失败");
                }
              });
            }
          });
        })
        .catch(() => { });
    },
    save(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          // 添加仓库名称
          this.formData.putInStorageList.forEach((item, index) => {
            if (item.stordocNo) {
              this.stordocList.forEach((item1) => {
                if (item1.stordocNo === item.stordocNo) {
                  this.formData.putInStorageList[index].stordocName =
                    item1.stordocName;
                }
              });
            }
          });
          if (this.nowChanceStau === "edit") {
            outStorage.edit(this.formData.putInStorageList[0]).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            console.log(this.formData.putInStorageList);
            this.formData.putInStorageList = this.formData.putInStorageList.map(item => {
              return {
                ...item,
                systemNo: sessionStorage.systemNo
              }
            })
            outStorage.batchAdd(this.formData.putInStorageList).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          } else if (this.nowChanceStau === "check") {
            outStorage.check(this.formData.putInStorageList[0]).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "审核成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "审核失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
@import "~@/styles/variables.scss";

.addone {
  margin-left: 140px;
}

.zhu {
  display: flex;

  ::v-deep .el-input__inner {
    background-color: rgb(241, 239, 239) !important;
  }
}

.numberUnit {
  display: flex;

  .one {
    width: 75%;
  }

  .two {
    width: 25%;
  }
}

.orderDetail {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;

  .w50p {
    padding: 0 5px;
  }
}

.btnlist {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}

.goods {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 10px;
}
</style>
